package MultithreadingTest;

import java.util.Arrays;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @ClassName TaskQueueRW
 * @Description TODO 读写锁
 * @Author ZhaoKai
 * @Date 2021-12-2009:20
 * @Version 1.0
 **/
public class TaskQueueRW {
    /*
     * 使用ReadWriteLock可以解决这个问题，它保证：
     *      1、只允许一个线程写入（其他线程既不能写入也不能读取）；
     *      2、没有写入时，多个线程允许同时读（提高性能）。
     */
    private final ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
    private final Lock readLock = readWriteLock.readLock();
    private final Lock writeLock = readWriteLock.writeLock();
    private int[] counts = new int[10];

    public void inc(int index) {
        writeLock.lock(); // 加写锁
        try {
            counts[index] += 1;
        } finally {
            writeLock.unlock(); // 释放写锁
        }
    }

    public int[] get() {
        readLock.lock(); // 加读锁
        try {
            return Arrays.copyOf(counts, counts.length);
        } finally {
            readLock.unlock(); // 释放读锁
        }
    }
}
